package xx.iverson.video_manage.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import xx.iverson.video_manage.entity.CategoryLevel1;
import xx.iverson.video_manage.entity.CategoryLevel2;
import xx.iverson.video_manage.entity.Video;
import xx.iverson.video_manage.mapper.IndexMapper;
import xx.iverson.video_manage.mapper.VideoMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * xx.iverson.video_manage.controller.Controller
 * <p>
 * on 2024/12/12
 *
 * @author weijx
 */
@Controller
public class IndexController {

    @Resource
    private IndexMapper indexMapper;

    @Resource
    private VideoMapper videoMapper;

    @RequestMapping("/")
    public String index(@RequestParam(value = "subcategory_id", defaultValue = "1") int subcategoryId,
                        @RequestParam(value = "query", defaultValue = "") String query,
                        Model model) {
        model.addAttribute("title", indexMapper.selectTitle());

        // 获取所有的顶级分类及其子分类
        List<CategoryLevel1> categories = indexMapper.selectAllWithSubcategories();
        model.addAttribute("categories_level_1", categories);

        // 找到当前显示的二级分类名称
        Optional<String> currentSubcategoryName = categories.stream()
                .filter(category -> category.getSubcategories() != null)
                .flatMap(category -> category.getSubcategories().stream())
                .filter(subcategory -> subcategory != null && subcategory.getId() == subcategoryId)
                .map(CategoryLevel2::getName)
                .findFirst();

        // 根据 subcategoryId 查询视频数据
        List<Video> videos;
        if (query.isEmpty()) {
            if (subcategoryId==1){
                videos = videoMapper.selectAll();
                // 如果找到了对应的二级分类名称，则添加到模型中
                if (currentSubcategoryName.isPresent()) {
                    model.addAttribute("current_subcategory_name", currentSubcategoryName.get());
                }else {
                    model.addAttribute("current_subcategory_name", "默认分类");
                }
            }else {
                videos=videoMapper.selectBySubcategoryId(subcategoryId);
            }
        } else {
            model.addAttribute("current_subcategory_name", query);
            videos = indexMapper.searchByTitle(query);
        }
        model.addAttribute("videos", videos);
        model.addAttribute("subcategory_id", subcategoryId);


        return "index";
    }

}